<template>
  <div class="count-box">
    <button class="minus" @click="sub">-</button>
    <input type="text" class="inp" :value="modelValu" @change="handleChange" />
    <button class="minus" @click="add">+</button>
  </div>
</template>

<script>
export default {
  props: {
    modelValu: {
      type: Number,
      default: 1
    }
  },
  methods: {
    add() {
      this.$emit('update:modelValu', this.modelValu + 1)
    },
    sub() {
      if (this.modelValue <= 1) {
        return
      }
      this.$emit('update:modelValu', this.modelValu - 1)
    },
    handleChange(e) {
      // console.log(e.target.value)
      // 字符串转数字
      // 判断小数
      const num = +e.target.value
      if (isNaN(num) || num < 1 || String(num).indexOf('.') + 1) {
        e.target.value = this.modelValu
        return
      }
      this.$emit('update:modelValu', num)
    }
  }
}
</script>

<style scoped lang="less">
.count-box {
  width: 110px;
  height: 30px;
  display: flex;
  .minus {
    width: 30px;
    height: 30px;
    outline: none;
    border: none;
    background-color: #efefef;
  }
  .inp {
    width: 40px;
    height: 30px;
    outline: none;
    border: none;
    margin: 0 5px;
    text-align: center;
    background-color: #efefef;
  }
}
</style>
